﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Net.Sockets;

namespace AgilePlannerDT.Persister.Impl.Socket
{
    public class SocketConnection : IConnection
    {
        TcpClient client;

        public SocketConnection(String url, int port)
        {
            client = new TcpClient(AddressFamily.InterNetwork);
            client.NoDelay = true;
            client.Connect(url, port);
        }

        public void send(byte[] msg)
        {
            try
            {
            
                client.GetStream().Write(msg, 0, msg.Length);

            } 
            catch(InvalidOperationException e)
            {
                //cannot communicate with the server, close the client
                client.Close();
            }
    }

        public byte[] read(int length)
        {
            byte [] ret = new byte[length];
            int offset = 0;
            while (offset < length)
                offset += client.GetStream().Read(ret, offset, length - offset);
            return ret;
        }


        public void close()
        {
            client.Close();
        }
    }
}
